package com.company;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by tu on 2017/7/3.
 */
@Configuration
public class RedisConfig {

  @Bean("jedis.config")
  public JedisPoolConfig jedisPoolConfig(
      @Value("${spring.redis.pool.max-total}") int maxTotal,
      @Value("${spring.redis.pool.min-idle}") int minIdle,
      @Value("${spring.redis.pool.max-idle}") int maxIdle,
      @Value("${spring.redis.pool.max-wait}") int maxWaitMillis) {

    JedisPoolConfig config = new JedisPoolConfig();
    config.setMinIdle(minIdle);
    config.setMaxIdle(maxIdle);
    config.setMaxWaitMillis(maxWaitMillis);
    config.setMaxTotal(maxTotal);
    //fixed Unexpected end of stream see https://github.com/xetorthio/jedis/issues/1029
    config.setTestOnBorrow(true);
    config.setTestOnReturn(true);
    return config;
  }

  @Bean
  public JedisPool jedisPool(
      @Qualifier("jedis.config") JedisPoolConfig config, @Value("${spring.redis.host}") String host,
      @Value("${spring.redis.port}") int port, @Value("${spring.redis.timeout}") int timeout,
      @Value("${spring.redis.password}") String password) {
    return new JedisPool(config, host, port, timeout, password);
  }
}
